package controllable_component;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import ball.Ball;
import util.Contents;
import util.Functions;
import barrier.Barrier;
/*
 * 挡板类，用户可以移动、旋转挡板来和球碰撞
 */
public class Plate extends Barrier {
	private double vx;	// 挡板在X方向上的最大速度
	private double vy;	// 挡板在X方向上的最大

	public Plate(double x, double y, int size) {
		super(2, "Plate", x, y, 2, 0.5, size);
		this.vx = Contents.PLATE_VELOCITY_X;
		this.vy = Contents.PLATE_VELOCITY_Y;
		// 设置板子速度上限
		try {
			this.img = ImageIO.read(new File(Contents.PLATE_IMG_PATH));
		} catch (IOException e) {
			System.out.println("PLATE_IMG read error");
		}
		// 加载板子图片
	}

	//判断球是否与挡板发生了碰撞
	@Override
	public void isCollided(Ball b) {
		// TODO Auto-generated method stub
		double bx = b.getNextX(), by = b.getNextY();
		double bex = b.getNextEx(), bey = b.getNextEy();
		double bcx = (bx + bex) / 2.0, bcy = (by + bey) / 2.0;
		double br = b.getDiameter() / 2.0;
		double bvx = b.getVx(), bvy = b.getVy();
		if ((bcy >= y && bcy <= ey) && ((bcx - x) * (bex - x) <= 0 || (bcx - ex) * (bx - ex) <= 0))
			b.changeV(-bvx, bvy, Contents.LOSS_COEFFICIENT);
		else if ((bcx >= x && bcx <= ex) && ((bcy - y) * (bey - y) <= 0 || (bcy - ey) * (by - ey) <= 0))
			b.changeV(bvx, -bvy, Contents.LOSS_COEFFICIENT);
		else if ((bcx - x) * (bcx - x) + (bcy - y) * (bcy - y) <= br * br)
			b.changeVByAngle(45, 1);
		else if ((bcx - ex) * (bcx - ex) + (bcy - ey) * (bcy - ey) <= br * br)
			b.changeVByAngle(225, 1);
		else if ((bcx - ex) * (bcx - ex) + (bcy - y) * (bcy - y) <= br * br)
			b.changeVByAngle(135, 1);
		else if ((bcx - x) * (bcx - x) + (bcy - ey) * (bcy - ey) <= br * br)
			b.changeVByAngle(315, 1);
	}

	//控制挡板旋转
	@Override
	public boolean rotate() {
		// TODO Auto-generated method stub
		angle = (angle + 1) % imgT;
		if (x + size * Contents.LATTICE_SIZE * by <= Contents.ALL_LATTICE_WIDTH
				&& y + size * Contents.LATTICE_SIZE * bx <= Contents.ALL_LATTICE_HEIGHT) {
			double temp;
			temp = bx;
			bx = by;
			by = temp;
			changeEx();
			changeEy();
			img = Functions.rotateClockwise90(img);
			return true;
		}
		return false;
	}

	//控制挡板向左移动
	public void moveLeft() {
		if (x - vx * Contents.DT > 0) {
			x -= vx * Contents.DT * 5;
			changeEx();
		}

	}

	//控制挡板向右移动
	public void moveRight() {
		if (ex + vx * Contents.DT < Contents.ALL_LATTICE_WIDTH) {
			x += vx * Contents.DT * 5;
			changeEx();
		}
	}

	//控制挡板向上移动
	public void moveUp() {
		if (y - vy * Contents.DT > 0) {
			y -= vy * Contents.DT;
			changeEy();
		}

	}

	//控制挡板向下移动
	public void moveDown() {
		if (ey + vy * Contents.DT < Contents.ALL_LATTICE_HEIGHT) {
			y += vy * Contents.DT;
			changeEy();
		}
	}

}
